from sqlalchemy import select

from forward.dependencies.database import db
from forward.model.tables.notice import NoticeSettingModel
from forward.plugins.notice.engine.sms_notice import SmsNotice
from forward.plugins.notice.schema.notice import NoticeSettingSchema
from forward.plugins.notice.template.sms_template import SmsTemplate


class NoticeDriver(object):
    async def handle(self, notice_params: dict):
        """
        notice_params:   {
                            "scene": send_params.scene,
                            "mobile": send_params.mobile,
                            "params":  {"code": ToolsUtil.random_int(4)}
                        }
        :param notice_params:
        :return:
        """
        scene = notice_params.get("scene")
        # 获取场景模板
        notice_record = await db.fetch_one(
            select(
                NoticeSettingModel.id,
                NoticeSettingModel.type,
                NoticeSettingModel.sms_notice,
            )
            .select_from(NoticeSettingModel)
            .where(NoticeSettingModel.scene == scene, NoticeSettingModel.is_delete == 0)
            .order_by(NoticeSettingModel.id.desc())
        )
        assert notice_record, "消息场景不存在!"
        notice = NoticeSettingSchema.model_validate(notice_record, from_attributes=True)
        sms_template = SmsTemplate(notice.type, notice.sms_notice)

        if sms_template.status and sms_template.status == 1:
            await SmsNotice().send(notice_params, sms_template)
